import os
import re

import docx
from docx import Document
from flask import Blueprint, render_template, request, jsonify

from config import UPLOADED_PHOTOS_DEST
from module_admin.entity.do.assigment import Assignment
from module_admin.entity.do.base import db
from module_admin.entity.do.file import File
from module_admin.entity.do.progress import Progress, VideoProgress
from module_admin.entity.do.submission import Submission

from module_admin.utils.http import fail_api, success_api, table_api
from module_admin.utils.validate import str_escape

assignment = Blueprint('assignment', __name__)


@assignment.route('/ass', methods=['GET', 'POST'])
def Ass():
    print(111)
    if request.method == 'GET':
        return render_template('Assignment.html')


@assignment.post('/add_assignment')
def add_assignment():
    req_json = request.get_json(force=True)
    title = str_escape(req_json.get('title'))
    description = str_escape(req_json.get('description'))
    course_id = req_json.get('course_id')
    created_by = str_escape(req_json.get('created_by', ''))

    if not title or not course_id:
        return fail_api(msg="作业标题和课程ID不得为空")

    assignment = Assignment(
        title=title,
        description=description,
        course_id=course_id,
        created_by=created_by
    )
    db.session.add(assignment)
    db.session.commit()
    return success_api(msg="作业添加成功")


@assignment.get('/assignment_list')
def get_all_assignments():
    # 查询所有作业
    assignments = Assignment.query.all()

    # 构建返回数据
    assignment_list = [
        {
            "id": assignment.id,
            "title": assignment.title,
            "description": assignment.description,
            "course_id": assignment.course_id,
            "created_by": assignment.created_by
        }
        for assignment in assignments
    ]

    return table_api(data=assignment_list, msg="获取作业列表成功")


@assignment.post('/edit_assignment/<int:assignment_id>')
def edit_assignment(assignment_id):
    req_json = request.get_json(force=True)
    new_title = str_escape(req_json.get('title'))
    new_description = str_escape(req_json.get('description'))
    new_course_id = req_json.get('course_id')
    new_created_by = str_escape(req_json.get('created_by'))

    # 查找指定作业
    assignment = Assignment.query.filter_by(id=assignment_id).first()

    if not assignment:
        return fail_api(msg="作业不存在")

    # 更新作业信息
    if new_title:
        assignment.title = new_title
    if new_description:
        assignment.description = new_description
    if new_course_id:
        assignment.course_id = new_course_id
    if new_created_by:
        assignment.created_by = new_created_by

    db.session.commit()
    return success_api(msg="作业编辑成功")


@assignment.get('/delete_assignment/<int:assignment_id>')
def delete_assignment(assignment_id):
    # 查找指定作业
    assignment = Assignment.query.filter_by(id=assignment_id).first()

    if not assignment:
        return fail_api(msg="作业不存在")

    # 删除作业
    db.session.delete(assignment)
    db.session.commit()

    return success_api(msg="作业删除成功")


# 读取 docx 文件内容
# def read_docx(file_path):
#     doc = Document(file_path)
#     questions = []
#     current_question = {}
#
#     for paragraph in doc.paragraphs:
#         text = paragraph.text.strip()
#
#         # 匹配问题行（以数字开头并以句号结束）
#         question_match = re.match(r'^\d+\.\s+(.*)', text)
#         if question_match:
#             if current_question:  # 如果已经有问题，先保存
#                 questions.append(current_question)
#             current_question = {"question": question_match.group(1), "options": {}, "correct_answer": ""}
#
#         # 匹配选项行
#         option_match = re.match(r'^[a-d]\)\s+(.*)', text)
#         if option_match and current_question:  # 如果是选项行且当前有问题
#             option_key = text[0]  # 取选项的标识符（a, b, c, d）
#             current_question["options"][option_key] = option_match.group(1)  # 提取选项文本
#
#     # 处理最后一个问题
#     if current_question:
#         questions.append(current_question)
#
#     return questions
#
#
# # 创建一个路由来读取 static 文件夹中的 .docx 文件
# @assignment.route('/read_docx/<filename>', methods=['GET'])
# def read_docx_file(filename):
#     if not filename.endswith('.docx'):
#         return jsonify({"error": "Invalid file type. Only .docx files are allowed."}), 400
#
#     file_path = os.path.join(UPLOADED_PHOTOS_DEST, filename)
#
#     if os.path.exists(file_path):
#         try:
#             # 读取 docx 文件内容
#             content = read_docx(file_path)
#             return jsonify({"filename": filename, "content": content}), 200
#         except Exception as e:
#             return jsonify({"error": str(e)}), 500
#     else:
#         return jsonify({"error": "File not found"}), 404

def read_docx(file_path):
    doc = Document(file_path)
    questions = []
    current_question = {}
    question_number = 1  # 题目编号从 1 开始

    for paragraph in doc.paragraphs:
        text = paragraph.text.strip()

        # 匹配问题行（以数字开头并以句号结束）
        question_match = re.match(r'^\d+\.\s+(.*)', text)
        if question_match:
            if current_question:  # 如果已经有问题，先保存
                questions.append(current_question)
            current_question = {
                "question": question_match.group(1),
                "options": {},
                "correct_answer": "",
                "question_number": question_number  # 添加题目编号
            }
            question_number += 1  # 题目编号递增

        # 匹配选项行
        option_match = re.match(r'^[a-d]\)\s+(.*)', text)
        if option_match and current_question:  # 如果是选项行且当前有问题
            option_key = text[0]  # 取选项的标识符（a, b, c, d）
            current_question["options"][option_key] = option_match.group(1)  # 提取选项文本

    # 处理最后一个问题
    if current_question:
        questions.append(current_question)

    total_questions = len(questions)  # 计算总题数
    return questions, total_questions


@assignment.route('/read_docx/<filename>', methods=['GET'])
def read_docx_file(filename):
    if not filename.endswith('.docx'):
        return jsonify({"error": "Invalid file type. Only .docx files are allowed."}), 400

    file_path = os.path.join(UPLOADED_PHOTOS_DEST, filename)

    if os.path.exists(file_path):
        try:
            # 读取 docx 文件内容
            content, total_questions = read_docx(file_path)
            return jsonify({"filename": filename, "content": content, "total_questions": total_questions}), 200
        except Exception as e:
            return jsonify({"error": str(e)}), 500
    else:
        return jsonify({"error": "File not found"}), 404


@assignment.route('/upload/word', methods=['POST'])
def upload_file():
    if 'file' not in request.files:
        return jsonify({'error': 'No file part'}), 400

    file = request.files['file']

    if file.filename == '':
        return jsonify({'error': 'No selected file'}), 400

    if file and file.filename.endswith('.docx'):
        file_path = os.path.join(UPLOADED_PHOTOS_DEST, file.filename)
        file.save(file_path)

        # 读取文件并解析
        try:
            formatted_questions = read_docx(file_path)
            # 假设最后一个选项是正确答案
            for question in formatted_questions:
                question["correct_answer"] = list(question["options"].keys())[-1]  # 最后一个选项作为正确答案

            return jsonify({"content": formatted_questions, "filename": file.filename}), 200
        except Exception as e:
            return jsonify({'error': str(e)}), 500
    else:
        return jsonify({'error': 'Invalid file format'}), 400


# 读取 docx 文件内容
def read_docx_to_list(file_path):
    # 打开并读取文档
    doc = Document(file_path)
    lines = []

    # 遍历每一段，将每段文本加入到列表中
    for para in doc.paragraphs:
        text = para.text.strip()  # 去除每段首尾空白字符
        if text:  # 仅将非空段落添加到列表中
            lines.append(text)

    return lines


@assignment.route('/progress/commit', methods=['POST'])
def add_progress():
    # 获取 JSON 数据
    data = request.get_json()
    answer = data['answer']
    file_id = data['file_id']
    print(answer)

    file_path = os.path.join(UPLOADED_PHOTOS_DEST, 'answer.docx')
    content_list = read_docx_to_list(file_path)
    print(content_list)

    # 初始化分数
    score = 0

    # 按索引比较 answer 和 content_list
    for i in range(min(len(answer), len(content_list))):
        if answer[i] == content_list[i]:
            score += 10  # 相同则加 10 分
    print(score)

    # 检查必需字段
    if not all(key in data for key in ('time', 'assignment_score', 'student_name')):
        return jsonify({"error": "Missing fields"}), 400

    # 创建 Progress 实例
    new_progress = Progress(
        quiz_score=score,
        time=data['time'],
        assignment_score=score,
        student_name=data['student_name'],
        course_name="英语",
        file_id=file_id
    )

    # 添加到数据库
    db.session.add(new_progress)

    new_submission = Submission(
        submission_file='111.docx',
        grade=data['assignment_score'],
        assignment_id="1",
        student_name=data['student_name'],

    )
    # 添加到数据库
    db.session.add(new_submission)
    data = {"score": score}
    try:
        db.session.commit()
        return table_api(data=data)
    except Exception as e:
        db.session.rollback()
        return jsonify({"error": str(e)}), 500


@assignment.route('/progress/get', methods=['GET'])
def get_all_progress():
    try:
        # 查询所有数据
        all_progress = Progress.query.all()

        # 格式化数据
        progress_list = [
            {
                "id": progress.id,
                "quiz_score": progress.quiz_score,
                "time": progress.time,
                "assignment_score": progress.assignment_score,
                "student_name": progress.student_name,
                "course_name": progress.course_name
            }
            for progress in all_progress
        ]
        return table_api(data=progress_list)
        # return jsonify(progress_list), 200
    except Exception as e:
        return jsonify({"error": str(e)}), 500


@assignment.route('/student/performance', methods=['GET'])
def student_performance():
    student_name = request.args.get('student_name')

    if not student_name:
        return jsonify({"error": "Missing student_name parameter"}), 400

    # 计算所有类型为 'test' 的文件数量
    total_files_count = File.query.filter(File.type == 'test').count()

    # 如果没有文件，直接返回
    if total_files_count == 0:
        return jsonify({"student_name": student_name, "percentage": 0}), 200

    # 计算该学生提交的文件数量
    submitted_count = Submission.query.filter(Submission.student_name == student_name).count()

    # 计算该学生提交的文件数量
    score_list = Progress.query.filter(Progress.student_name == student_name).all()
    print(score_list)
    data = []
    for score in score_list:
        data1 = {
            'name': score.student_name,
            'score': score.quiz_score,
            'created_at': score.created_at,
            'file_id': score.file_id,
        }
        data.append(data1)

    # 计算百分比
    percentage = (submitted_count / total_files_count) * 100

    # 确保百分比不超过100
    if percentage > 100:
        percentage = 100

    # 查找第一个视频文件
    video_file = VideoProgress.query.filter(VideoProgress.student_name == student_name).first()
    # print(video_file.size)
    if not video_file:
        return jsonify(
            {"student_name": student_name, "percentage": percentage, "process": 0, "score_list": data}), 200

    return jsonify({"student_name": student_name, "percentage": percentage, "process": video_file.video_progress,
                    "score_list": data}), 200


@assignment.route('/update_video_file', methods=['POST'])
def update_video_file():
    data = request.json
    progress = data.get('progress')
    new_size = data.get('size')
    filename = data.get('filename')
    user_name = data.get('user_name')

    # if progress is None or filename is None:
    #     return jsonify({'error': '缺少必要的参数'}), 400

    # 查找第一个视频文件
    print(filename, user_name)
    # video_file = File.query.filter(File.original_name == filename,
    #                                File.user_name == user_name).first()

    # if not video_file:
    #     return jsonify({'message': '未找到视频文件'}), 400

    student_progress = VideoProgress.query.filter(VideoProgress.student_name == user_name).first()
    # print(student_progress.s)
    if not student_progress:
        if progress > 100:
            progress = 100
        # 创建 Progress 实例
        new_progress = VideoProgress(
            video_progress=progress,
            student_name=user_name,
            file_name='111'
        )

        # 添加到数据库
        db.session.add(new_progress)
        db.session.commit()
        return jsonify({"progress": progress}), 200
    else:
        # 如果 size 为空或 0，设置新的 size
        if progress > 100:
            progress = 100

        student_progress.video_progress = progress
        db.session.commit()
        return jsonify({"progress": progress}), 200
    # 文件名不一致，则返回不更新信息
    # if video_file.original_name != filename:
    #     return jsonify({
    #         'message': '文件名不匹配，不需要更新',
    #         'current_file': {
    #             'id': video_file.id,
    #             'original_name': video_file.original_name,
    #             'size': video_file.size,
    #             'progress': progress
    #         }
    #     }), 200

    # 检查 size 字段的值
    # if video_file.size is None or video_file.size == 0:
    #     # 如果 size 为空或 0，设置新的 size
    #     video_file.size = new_size
    #     video_file.user_name = user_name
    #     video_file.type = "video"
    #     db.session.commit()
    #
    #     student_progress.video_progress = progress
    #     student_progress.student_name = user_name
    #     student_progress.file_name = filename
    #     db.session.commit()
    #     return jsonify({'message': '文件大小已保存', 'file_id': video_file.id}), 200
    # elif video_file.size < new_size:
    #     # 如果 size 小于新 size，不需要更新
    #     return jsonify({'message': '文件大小较小，无需更新', 'file_id': video_file.id}), 200
    # else:
    #     # 如果 size 大于新 size，需要更新
    #     video_file.size = new_size
    #     db.session.commit()
    #     student_progress.video_progress = progress
    #     student_progress.student_name = user_name
    #     student_progress.file_name = filename
    #     db.session.commit()
    #     return jsonify({'message': '文件大小已更新', 'file_id': video_file.id}), 200
